use std::{io::{stdin, self, Write}, thread};

pub fn quit_confirm() -> bool {
    let line = do_read_line();
    line == "Y" || line == "y"
}
pub fn do_read_amount() -> i32 {
    loop {
        let line = do_read_line();
        let i: i32 = match line.parse() {
            Ok(i) => i,
            Err(_) => {
                println!("请输入合法数据");
                continue;
            }
        };
        return i;
    }
}
/// 读取键盘输入的菜单选项，进行合法性校验
pub fn read_menu_selection(i: i32) -> char {
    loop {
        let line = do_read_line();
        if line.len() == 1 {
            let ch = line.chars().nth(0).unwrap();
            let n = ch as i32 - '0' as i32;
            if 1 <= n && n <= i {
                return ch;
            }
        }
        println!("请输入合法内容");
    }
}
pub fn do_read_detail() -> String {
    loop {
        let detail = do_read_line();
        if detail.contains(",;,") {
            println!("输入内容不可以包含 ,;, ")
        } else {
            return detail;
        }
    }
}

// 按回车键继续
pub fn do_enter_key_continue() {
    println!("\n按回车键继续。。。");
    thread::sleep(std::time::Duration::from_millis(100));
    do_read_line();
}
fn do_read_line() -> String {
    let mut line = String::new();
    io::stdout().flush().unwrap();
    stdin().read_line(&mut line).expect("无法读取输入行");
    line.trim().to_string()
}

#[cfg(test)]
mod test {
    use crate::read_input::{quit_confirm, read_menu_selection};

    #[test]
    pub fn read_menu_selection_test() {
        let ch = read_menu_selection(3);
        println!("{}", ch);
    }

    #[test]
    pub fn quit_confirm_test() {
        let ch = quit_confirm();
        println!("{}", ch);
    }
}
